package com.link.play.fit.ai.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;

import androidx.annotation.ColorInt;
import androidx.appcompat.widget.AppCompatTextView;

import com.link.play.fit.ai.R;

public class StrokeTextView extends AppCompatTextView {
    private Paint mStrokePaint = new Paint();
    private int mStrokeColor = Color.BLACK;
    private float mStrokeWidth = 5f;

    public StrokeTextView(Context context) {
        super(context);
        init();
    }

    public StrokeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttrs(context, attrs);
        init();
    }

    public StrokeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttrs(context, attrs);
        init();
    }

    private void initAttrs(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.StrokeTextView);
        mStrokeColor = a.getColor(R.styleable.StrokeTextView_strokeColor, Color.BLACK);
        mStrokeWidth = a.getDimension(R.styleable.StrokeTextView_strokeWidth, 5f);
        a.recycle();
    }

    private void init() {
        // 初始化描边画笔
        mStrokePaint.setAntiAlias(true);
        mStrokePaint.setStyle(Paint.Style.STROKE);
        mStrokePaint.setColor(mStrokeColor);
        mStrokePaint.setStrokeWidth(mStrokeWidth);
        mStrokePaint.setTextSize(getTextSize());
        mStrokePaint.setTypeface(getTypeface());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 先绘制描边
        mStrokePaint.setColor(mStrokeColor);
        String text = getText().toString();
        canvas.drawText(text,
                (getWidth() - mStrokePaint.measureText(text)) / 2,
                getBaseline(),
                mStrokePaint);

        // 再绘制原始文字（覆盖填充）
        super.onDraw(canvas);
    }

    // 动态设置描边颜色的方法
    public void setStrokeColor(@ColorInt int color) {
        mStrokeColor = color;
        invalidate();
    }

    // 动态设置描边宽度的方法
    public void setStrokeWidth(float width) {
        mStrokeWidth = width;
        mStrokePaint.setStrokeWidth(width);
        invalidate();
    }
}